import 'package:app_router_demo/pages/home/models/home_list_model.dart';
import 'package:app_router_demo/providers/home_provider.dart';
import 'package:auto_route/auto_route.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

@RoutePage()
class HomeListPage extends StatefulWidget {
  const HomeListPage({super.key});

  @override
  State<HomeListPage> createState() => _HomeListPageState();
}

class _HomeListPageState extends State<HomeListPage> {
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }

  void _onScroll() {
    if (_scrollController.position.pixels ==
        _scrollController.position.maxScrollExtent) {
      // 滚动到底部，加载更多
      Provider.of<HomeListProvider>(context, listen: false).fetchItems();
    }
  }

  Future<void> _onRefresh() async {
    await Provider.of<HomeListProvider>(
      context,
      listen: false,
    ).fetchItems(isRefresh: true);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Consumer<HomeListProvider>(
        builder: (context, provider, child) {
          if (provider.errorMessage != null && provider.items.isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text('加载失败: ${provider.errorMessage}'),
                  ElevatedButton(
                    onPressed: () => provider.fetchItems(isRefresh: true),
                    child: const Text('重试'),
                  ),
                ],
              ),
            );
          }

          if (provider.isLoading && provider.items.isEmpty) {
            return const Center(child: CircularProgressIndicator());
          }

          if (provider.items.isEmpty && !provider.isLoading) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  const Text('暂无数据'),
                  ElevatedButton(
                    onPressed: () => provider.fetchItems(isRefresh: true),
                    child: const Text('点击加载'),
                  ),
                ],
              ),
            );
          }

          return RefreshIndicator(
            onRefresh: _onRefresh,
            child:
                provider.isList
                    ? _listViewWidget(provider)
                    : _buildGridViewItem(provider),
          );
        },
      ),
    );
  }

  Widget _buildGridViewItem(HomeListProvider provider) {
    return GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 2, // 两列网格
        crossAxisSpacing: 12, // 列间距
        mainAxisSpacing: 12, // 行间距
        childAspectRatio: 170 / 228.0, // 宽高比控制
      ),
      padding: EdgeInsets.all(12), // 整体边距
      itemCount: provider.items.length + (provider.hasMore ? 1 : 0), // 数据总量（必须）
      itemBuilder: (context, index) {
        if (index < provider.items.length) {
          return _buildCharacterCard(provider.items[index]);
        } else {
          // 加载更多指示器
          return Padding(
            padding: const EdgeInsets.all(16.0),
            child: Center(
              child:
                  provider.isLoading
                      ? const CircularProgressIndicator()
                      : const Text('没有更多数据了'),
            ),
          );
        }
        // 动态构建子项
      },
    );
  }

  Widget _buildUserListItem(HomeListModel user) {
    return Material(
      child: Container(
        height: 88,
        margin: const EdgeInsets.only(left: 12.0, right: 12, top: 12),
        padding: const EdgeInsets.all(12.0),
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(16.0),
        ),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            // 左侧头像
            CachedNetworkImage(
              imageUrl: user.icon,
              placeholder:
                  (context, url) => Container(color: Color(0xfff8f8f8)),
              imageBuilder:
                  (context, imageProvider) => Container(
                    width: 64, // 头像直径
                    height: 64,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      image: DecorationImage(
                        image: imageProvider,
                        fit: BoxFit.cover, // 图片填充模式
                      ),
                    ),
                  ),
            ),
            const SizedBox(width: 12),
            // 中间信息
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  // 昵称、状态图标和国家
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center, // 保持居中对齐
                    children: [
                      Expanded(
                        // <-- 关键修改：在这里添加 Expanded
                        child: Text(
                          user.name,
                          style: const TextStyle(
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                            color: Colors.black87,
                          ),
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                      const SizedBox(width: 6),
                      // 状态图标 (例如：绿勾，红星)
                      // if (user.onlineStatus == 1)
                      //   Row(
                      //     children:
                      //         user.onlineStatus!.map((iconUrl) {
                      //           // 这里根据 iconUrl 或 iconType 显示不同的图标
                      //           // 假设 'check' 和 'star' 是图标类型
                      //           if (iconUrl == 'check') {
                      //             return Icon(
                      //               Icons.check_circle,
                      //               color: Colors.green,
                      //               size: 18,
                      //             );
                      //           } else if (iconUrl == 'star') {
                      //             return Icon(
                      //               Icons.star,
                      //               color: Colors.orange,
                      //               size: 18,
                      //             );
                      //           }
                      //           // 默认显示一个问号图标或者加载网络图片
                      //           return SizedBox(
                      //             width: 18,
                      //             height: 18,
                      //             child: Image.network(
                      //               iconUrl, // 如果statusIcons是图片URL
                      //               errorBuilder:
                      //                   (context, error, stackTrace) =>
                      //                       const Icon(Icons.help_outline),
                      //             ),
                      //           );
                      //         }).toList(),
                      //   ),
                      const SizedBox(width: 8),
                      // 国家图标和年龄
                      Row(
                        children: [
                          // 国家图标
                          Image.network(
                            user.countryFlag,
                            width: 20,
                            height: 14,
                            fit: BoxFit.cover,
                            errorBuilder:
                                (context, error, stackTrace) =>
                                    const Icon(Icons.flag_outlined, size: 20),
                          ),
                          const SizedBox(width: 4),
                          // 年龄
                          Text(
                            '16',
                            style: const TextStyle(
                              fontSize: 13,
                              color: Colors.grey,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                  const SizedBox(height: 4),
                  // 签名/描述
                  Text(
                    "heihi",
                    style: const TextStyle(fontSize: 14, color: Colors.grey),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ],
              ),
            ),
            const SizedBox(width: 12),
            // 右侧按钮
            IconButton(
              onPressed: () {
                // 处理按钮点击事件
              },
              icon: Image.asset(
                "assets/images/vz_syhi.png",
                width: 64,
                height: 32,
                fit: BoxFit.cover,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Widget _buildActionButton(HomeListModel user) {
  //   if (user.actionButtonText == 'Hi' || user.actionButtonText == 'Chat') {
  //     return Container(
  //       padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
  //       decoration: BoxDecoration(
  //         color: user.actionButtonText == 'Hi' ? Colors.purple[100] : Colors.pink[100],
  //         borderRadius: BorderRadius.circular(20),
  //       ),
  //       child: Row(
  //         mainAxisSize: MainAxisSize.min,
  //         children: [
  //           if (user.actionButtonText == 'Hi')
  //             Icon(Icons.favorite, color: Colors.purple, size: 18)
  //           else if (user.actionButtonText == 'Chat')
  //             Icon(Icons.message, color: Colors.pink, size: 18),
  //           const SizedBox(width: 4),
  //           Text(
  //             user.actionButtonText,
  //             style: TextStyle(
  //               color: user.actionButtonText == 'Hi' ? Colors.purple : Colors.pink,
  //               fontWeight: FontWeight.bold,
  //             ),
  //           ),
  //         ],
  //       ),
  //     );
  //   } else {
  //     // 默认的聊天图标按钮 (根据你的图片，可能是这种样式)
  //     return Container(
  //       width: 44, // 固定宽度
  //       height: 44, // 固定高度
  //       decoration: BoxDecoration(
  //         color: Colors.pink[100],
  //         borderRadius: BorderRadius.circular(22), // 半径为高度/宽度的一半，使其成为圆形
  //       ),
  //       child: const Icon(Icons.message, color: Colors.pink, size: 24),
  //     );
  //   }
  // }

  Widget _listViewWidget(HomeListProvider provider) {
    return ListView.builder(
      controller: _scrollController,
      itemCount: provider.items.length + (provider.hasMore ? 1 : 0),
      itemBuilder: (context, index) {
        if (index < provider.items.length) {
          final item = provider.items[index];
          return _buildUserListItem(item);
        } else {
          // 加载更多指示器
          return Padding(
            padding: const EdgeInsets.all(16.0),
            child: Center(
              child:
                  provider.isLoading
                      ? const CircularProgressIndicator()
                      : const Text('没有更多数据了'),
            ),
          );
        }
      },
    );
  }

  Widget _buildCharacterCard(HomeListModel model) {
    return Material(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(16),
        child: Stack(
          children: [
            // 背景图片
            Positioned.fill(
              child: CachedNetworkImage(
                imageUrl: model.icon,
                placeholder:
                    (context, url) => Container(color: Color(0xfff8f8f8)),
                fit: BoxFit.cover,
              ),
            ),
            Padding(
              padding: EdgeInsets.all(8),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Expanded(
                        // 移除 flex: 0，或者显式设置为 flex: 1
                        child: Text(
                          model.name,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ),
                      Container(
                        width: 12,
                        height: 12,
                        decoration: BoxDecoration(
                          color: Color(0xff36E179),
                          borderRadius: BorderRadius.circular(6),
                          border: Border.all(color: Colors.white, width: 1.5),
                        ),
                      ),
                    ],
                  ),
                  SizedBox(height: 4),
                  Image.asset(
                    "assets/images/vz_vistar.png",
                    width: 64,
                    height: 22,
                  ),
                ],
              ),
            ),
            Positioned(
              bottom: 12,
              left: 0,
              right: 0,
              child: Center(
                child: IconButton(
                  onPressed: () {},
                  icon: Image.asset(
                    "assets/images/vz_vistar.png",
                    width: 64,
                    height: 22,
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }
}
